﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Diagnostics;

namespace FritzToShrew
{
    public partial class MainForm : Form
    {
        public MainForm()
        {
            InitializeComponent();
        }

        private void btt_selSource_Click(object sender, EventArgs e)
        {
            string defaultPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
            if (!defaultPath.EndsWith("\\"))
            {
                defaultPath += "\\";
            }
            defaultPath += "AVM\\FRITZ!Fernzugang\\";

            if (Directory.Exists(defaultPath))
            {
                ofdSource.InitialDirectory = defaultPath;
            }            

            if (ofdSource.ShowDialog() == DialogResult.OK)
            {
                text_src.Text = ofdSource.FileName;

                if (text_dst.Text == "")
                {
                    string DstFilename = text_src.Text;
                    if (DstFilename.ToLowerInvariant().EndsWith(".cfg"))
                    {
                        DstFilename = DstFilename.Substring(0, DstFilename.Length - 4);
                    }
                    DstFilename += ".vpn";

                    text_dst.Text = DstFilename;
                }
            }
        }

        private void btt_selDest_Click(object sender, EventArgs e)
        {
            if (sfdDest.ShowDialog() == DialogResult.OK)
            {
                text_dst.Text = sfdDest.FileName;
            }
        }

        private string ExtractParameter(string line)
        {
            int eqPos = line.IndexOf("=");

            string line2 = line;
            if (line.EndsWith(";"))
            {
                line2 = line.Substring(0,line.Length-1);
            }

            string retval = "";

            if (eqPos > 0)
            {
                int sPos = eqPos+1;
                while ((sPos < line2.Length) && ((line2[sPos] == ' ') || (line2[sPos] == '"')))
                {
                    sPos++;
                }

                int ePos = line2.Length - 1;
                while ((ePos > sPos) && ((line2[ePos] == ' ') || (line2[ePos] == '"')))
                {
                    ePos--;
                }

                retval = line2.Substring(sPos, ePos - sPos +1 );
            }

            return retval;
        }

        private void btt_convert_Click(object sender, EventArgs e)
        {
            if (!File.Exists(text_src.Text))
            {
                MessageBox.Show("Quelldatei existiert nicht!", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            string destPath = text_dst.Text;
            int destPathEnd = destPath.LastIndexOf("\\");
            if (destPathEnd > 0)
            {
                destPath = destPath.Substring(0, destPathEnd);
            }

            if (Directory.Exists(text_dst.Text))
            {
                MessageBox.Show("Zieldatei: Ungültiger Pfad!", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            if (!Directory.Exists(destPath))
            {
                MessageBox.Show("Zielverzeichnis existiert nicht!", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            try
            {
                RealWork(destPath);
            }
            catch (Exception ex)
            {
                StringBuilder sb=new StringBuilder();
                sb.AppendLine("Es ist ein Fehler aufgetreten:");
                sb.AppendLine(ex.Message);
                sb.AppendLine();
                sb.AppendLine("StackTrace:");
                sb.AppendLine(ex.StackTrace);

                MessageBox.Show(sb.ToString(), Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void RealWork(string destPath)
        {
            string remotehostname = "";
            string user_fqdn = "";
            string key = "";
            string ipaddr = "";
            string mask = "";

            string[] lines = File.ReadAllLines(text_src.Text);

            bool validFile = false;
            for (int i = 0; i < lines.Length; i++)
            {
                string tLine = lines[i].Trim();

                if (validFile)
                {
                    if (tLine.StartsWith("remotehostname"))
                    {
                        remotehostname = ExtractParameter(tLine);
                    }
                    else if (tLine.StartsWith("user_fqdn"))
                    {
                        user_fqdn = ExtractParameter(tLine);
                    }
                    else if (tLine.StartsWith("key"))
                    {
                        key = ExtractParameter(tLine);
                    }
                    else if (tLine.StartsWith("ipaddr"))
                    {
                        ipaddr = ExtractParameter(tLine);
                    }
                    else if (tLine.StartsWith("mask"))
                    {
                        mask = ExtractParameter(tLine);
                    }
                }
                else
                {
                    if (tLine.StartsWith("targets"))
                    {
                        validFile = true;
                    }
                }
            }

            if (validFile)
            {
                byte[] keyBytes = Encoding.Default.GetBytes(key);

                string presharedkey = Convert.ToBase64String(keyBytes);

                string writeStr = Properties.Resources.template;
                writeStr = writeStr.Replace("##remotehostname##", remotehostname);
                writeStr = writeStr.Replace("##user_fqdn##", user_fqdn);
                writeStr = writeStr.Replace("##presharedkey##", presharedkey);
                writeStr = writeStr.Replace("##ipaddr##", ipaddr);
                writeStr = writeStr.Replace("##mask##", mask);

                if (File.Exists(text_dst.Text))
                {
                    StringBuilder sb = new StringBuilder();
                    sb.AppendLine("Die Datei '" + text_dst.Text + "' existiert bereits!");
                    sb.AppendLine("Soll die Datei überschrieben werden?");

                    if (MessageBox.Show(sb.ToString(), Application.ProductName, MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1) != DialogResult.Yes)
                    {
                        return;
                    }
                }

                File.WriteAllText(text_dst.Text, writeStr);

                {
                    StringBuilder sb = new StringBuilder();
                    sb.AppendLine("ShrewVPN Konfigurationsdatei wurde geschrieben.");
                    sb.AppendLine("Nach Klick auf OK sollte sich der Ordner mit der Konfigurationsdatei öffnen...");

                    MessageBox.Show(sb.ToString(), Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Information);
                }

                // Ordner öffnen:
                ProcessStartInfo psi = new ProcessStartInfo("explorer", destPath);
                Process p = Process.Start(psi);
            }
            else
            {
                MessageBox.Show("The file does not look like a valid FritzVPN Config-File!");
            }
        }
    }
}
